﻿using System;
using System.Collections.Generic;
using Sproto;
using USNetFramework.Network;

namespace USNetFramework.PacketBuilder
{
    public abstract class SPPacketBuilder : PacketBuilder
    {
        private static int MAX_GLOBALSPROTO = 16;

        protected List<SprotoMgr> SprotoList { private set; get; }

        public SPPacketBuilder() : base(true)
        {
            SprotoList = new List<SprotoMgr>();
        }

        public abstract void Init();

        #region Sproto List
        public void RegisterSproto(ushort _protoType, string _protoStr, string _name = null)
        {
            if (null == SprotoList)
                throw new Exception(@"RegisterSproto Error! Check SprotoList is Init in SPPacketBuilder()!");

            if (SprotoList.Count >= MAX_GLOBALSPROTO)
                throw new Exception(@"RegisterSproto Error! SprotoList count must less than 16");

            if (_protoType != SprotoList.Count)
                throw new Exception(@"RegisterSproto Error! SprotoList now can register _protoType ->" + SprotoList.Count + 1);

            if (_name == null)
                _name = string.Concat("Sproto_", _protoType);

            SprotoMgr sproto = SprotoParser.Parse(_protoStr, _name);
            SprotoList.Add(sproto);
        }

        public SprotoMgr GetSprotoMgr(ushort _protoType)
        {
            if (_protoType >= SprotoList.Count)
                throw new Exception(@"RegisterSproto Error! Check SprotoList is Init in SPPacketBuilder()!");
            return SprotoList[_protoType];
        }
        #endregion
    }
}
